<?php

namespace app\api\controller;

use app\common\lib\ChatGpt;
use app\common\lib\ChatGptBaidu;
use app\common\lib\Sensitive;
use hg\apidoc\annotation as Apidoc;
use hg\apidoc\annotation\Param;
use hg\apidoc\annotation\Query;
use hg\apidoc\annotation\Returned;
use hg\apidoc\annotation\Header;
use app\BaseController;
use think\App;
use think\facade\View;
use think\facade\Db;
use think\response\Json;
/**
 * 文章标题
 *
 * api-ArticleTitle
 *
 * @Apidoc\Title("文章标题")
 * @Apidoc\Group("api")
 */
class ArticleTitle extends BaseController
{

    /**
     * 获取标题
     *
     * api-ArticleTitle-getTitle
     *
     * NotHeaders
     * @Apidoc\Title("获取标题sse")
     * @Apidoc\Url("/api/ArticleTitle/getTitle")
     * @Apidoc\Method("get")
     * @Query("key_word",type="varchar",require=true,desc="关键词",mock="@city")
     * @Query("generated_quantity",type="int",require=true,desc="生成数量",mock="@integer(3, 8)")
     * @Query("event_name",type="varchar",require=true,desc="sse事件名称")
     * @Query("key", type="varchar", require=true, desc="getAccess接口成功返回的key")
     * @Returned("title", type="varchar",desc="文章标题 ")
     * @Returned("is_used", type="tinyint",desc="是否重复【0，1】")
     */
    public function getTitle()
    {
        /******************言论审查开始***********************************/
        //数据检验开始，这里审查用户的言论是否符合国家法律规定，这里一定要加上++++++++++++++++++++++++++++++++++++++++++++++++++++++
        $TextModeration=new \app\api\service\TextModerationService();
        if (!$TextModeration->check(json_encode($this->request->param(),JSON_UNESCAPED_UNICODE))) {
            return error($TextModeration->msg);
        }
        /*****************言论审查结束了**********************************/
        $event_name = input('event_name', 'chat', 'trim');
        if(!$event_name) {
            return error('事件名称能为空', []);
        }

        $key = input('key', '', 'trim');
        if(!$key || !cache($key)) {
            return error('key非法请求', []);
        }else{
            cache($key, null);
        }


        $key_word = input('key_word', 20, 'trim');
        $generated_quantity = input('generated_quantity', '', 'intval');
        if(!$key_word) {
            return error('关键词不能为空', []);
        }
        //生成语言
        $lang = input('generated_lang', '', 'trim');


        $query_str = "生成{$generated_quantity}个关于'{$key_word}'的文章标题,结果以如下格式返回,每个标题后面返回一个&&,结尾处也要有&&，请严格按照格式返回，不要多余字符。格式```文章标题&&文章标题&&文章标题&&```";
        if($lang){
            $query_str.=" 生成语言为```{$lang}```";
        }
        ChatGpt::chat($query_str,true,$event_name, true, 'sendEvent');

        //ChatGptBaidu::chat($query_str,true,$event_name, true, 'sendEvent');
        return 1;
    }


    /**
     * getAccess
     * @return Json|void
     *
     * NotHeaders
     * @Apidoc\Title("获取能否请求")
     * @Apidoc\Url("/api/ArticleTitle/getAccess")
     * @Apidoc\Method("post")
     * @Param("key_word",type="varchar",require=true,desc="关键词",mock="@city")
     * @Param("generated_quantity",type="int",require=true,desc="生成数量",mock="@integer(3, 8)")
     * @Returned("key", type="varchar",desc="用于获取标题的key")
     */
    public function getAccess()
    {
        /******************言论审查开始***********************************/
        //数据检验开始，这里审查用户的言论是否符合国家法律规定，这里一定要加上++++++++++++++++++++++++++++++++++++++++++++++++++++++
        $TextModeration=new \app\api\service\TextModerationService();
        if (!$TextModeration->check(json_encode($this->request->param(),JSON_UNESCAPED_UNICODE))) {
            return error($TextModeration->msg);
        }
        /*****************言论审查结束了**********************************/
        $key_word = input('key_word', 20, 'trim');
        $generated_quantity = input('generated_quantity', '', 'intval');
        if(!$key_word) {
            return error('关键词不能为空', []);
        }
        $res = Sensitive::has($key_word);
        if($res) {
            //return error('不能包含敏感词：'. Sensitive::get($key_word));
            return error('不能包含敏感词');
        }


        $today_range  = [
            strtotime(date('Y-m-d')),
            strtotime(date('Y-m-d')) + 60 * 60 * 24 -1,
        ];
        $ip_today_count = \app\common\model\ArticleTitle::where([
            ['ip_address'  ,'=', $this->request->ip()],
            ['create_time' ,'between', $today_range]
        ])->sum('generated_quantity');

        //todo 每个ip未登录每天请求条数
        $max_count_per_ip_per_day = config('user.title_num_per_day');
        if($ip_today_count + $generated_quantity > $max_count_per_ip_per_day ){
            return error('当日请求条数超出限制，请登录！', ['action' => 'login']);
        }

        \app\common\model\ArticleTitle::create([
            'key_word' => $key_word,
            'generated_quantity' => $generated_quantity,
            'member_id' => 0,
            'ip_address' => $this->request->ip()
        ]);

        $random_key = uniqid();
        cache($random_key, 1, ['expire' => 100]);
        return success('', ['key' => $random_key]);
    }

    public function get_gpt_strategy(): \think\response\Json
    {
        $res = \app\common\model\GptStrategy::order('sort' ,'asc')->select();
        $res = $res->toArray();
        return success('ok', $res);
    }
    /**
     * getTitlePages
     * @Apidoc\Title("获取生成标题条数配置")
     * @Apidoc\Method("post")
     * @Param("is_login",type="boolean",require=true,desc="是否已登录")
     * @Returned("value", type="varchar",desc="条数")
     * @Returned("disabled", type="boolean",desc="是否禁止")
     */
    public function getTitlePages()
    {
        $config_pages = config('user.title_pages');
        $res = [];
        $is_login = input('is_login');
        if($is_login) {
            foreach ($config_pages as $page) {
                $page['disabled'] = false;
                $res[] = $page;
            }
        }else{
            foreach ($config_pages as $page) {
                $page['disabled'] = $page['is_member'] ? true : false;
                $res[] = $page;
            }
        }
        return success('', $res);
    }

    /**
     * 获取生成语言
     * @Apidoc\Title("获取生成语言")
     * getLanguage
     */
    public function getLanguage()
    {
        $language = config('article_creation.language');
        $arr = explode("\r\n", trim($language));
        return success('', $arr);
    }
    /**
     * 获取每篇文章消耗积分
     * @Apidoc\Title("获取每篇文章消耗积分")
     * getArticlePoint
     */
    public function getArticlePoint()
    {
        return success('', config('user.point_per_article'));
    }
  
}
